<template>
  <div v-loading.fullscreen="loading">
    <el-row
      :gutter="10"
      class="marginTop10"
    >
      <input
        @change="fileChanged"
        type="file"
        id="weekInput"
        style="display:none"
        accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
      >
      <el-col
        :span="24"
        style="text-align: center;"
      >
        <el-button
          type="success"
          @click="addBtnClick"
          size="large"
        >上传菜单</el-button>
        <el-button
          type="success"
          @click="downloadBtnClick"
          size="large"
        >下载模板</el-button>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-calendar>
          <template
            #date-cell="{ data }"
            style="background-color: var(--el-color-success-light-5)"
          >
            <div :class="weekDays.includes(data.day) ? 'is-selected' : ''">
              <div>{{ data.day.replace(/-/g, '/') }}</div>

              <div v-if="weekDays.includes(data.day)">
                <div v-if="tableDatas.oritableData.length > 0">
                  <div v-for="row in tableDatas.oritableData">
                    {{ row[getKeyFromDate(data.day)]}}
                  </div>
                </div>
                <div v-else>
                  <div v-for="row in tableDatas.oriCalendarCdNameObj[data.day]">
                    {{ row }}
                  </div>
                </div>
              </div>

              <el-collapse v-else-if="['周一','周二','周三','周四','周五'].includes(getKeyFromDate(data.day))">
                <el-collapse-item
                  v-if="tableDatas.oriCalendarCdNameObj[data.day] && tableDatas.oriCalendarCdNameObj[data.day].length"
                  :title="`当日菜单(${tableDatas.oriCalendarCdNameObj[data.day].length})`"
                  name="1"
                >
                  <div>
                    <div v-for="row in tableDatas.oriCalendarCdNameObj[data.day]">
                      {{ row }}
                    </div>
                  </div>

                </el-collapse-item>
              </el-collapse>
            </div>
          </template>
        </el-calendar>
      </el-col>

      <!-- <el-col :span="12">
        <el-table
          class="marginTop48"
          :data="tableDatas.tableDatasAfterPage"
          stripe
          border
          empty-text="无数据"
          max-height="80vh"
        >
          <el-table-column
            v-for="column in tableDatas.tableColumns"
            :type="column.type"
            :prop="column.prop"
            :label="column.label"
            :align="column.align"
            :width="column.width"
          >

            <template
              #default="scope"
              v-if="column.prop =='URL'"
            >
              <div>
                <div v-if="scope.row.FULL_URL">
                  <img
                    style="width: 200px;height:100px"
                    :src="scope.row.FULL_URL + `?t=${Date.now()}`"
                  >
                </div>
                <div v-else>暂无图片</div>
              </div>
            </template>

            <template
              #default="scope"
              v-if="column.prop =='TYPE'"
            >
              <div>
                <el-checkbox
                  v-model="scope.row.TYPE"
                  true-value="固定"
                  false-value="不固定"
                  label="固定"
                  size="large"
                />
              </div>
            </template>

            <template
              #default="scope"
              v-if="column.prop =='operate'"
            >
              <div>
                <el-button
                  type="success"
                  @click="tableDatas.editBtnClick(scope.row)"
                >修改</el-button>
                <el-popconfirm
                  confirm-button-text="确定"
                  cancel-button-text="取消"
                  title="确定删除该条记录?"
                  @confirm="tableDatas.deleteBtnClick(scope.row)"
                >
                  <template #reference>
                    <el-button type="danger">删除</el-button>
                  </template>
                </el-popconfirm>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </el-col> -->

    </el-row>

    <el-row>
      <el-col style="text-align: center;">
        <el-button
          type="primary"
          @click="dialogDatas.confirmBtnClick"
          size="large"
        >确认上传</el-button>
      </el-col>
    </el-row>

    <el-dialog
      v-model="dialogDatas.dialogFormVisible"
      :title="dialogDatas.isNew ? '添加':'修改'"
      destroy-on-close
      top="5vh"
    >
      <el-scrollbar max-height="70vh">
        <el-form :model="dialogDatas.currentData">
          <el-form-item
            v-for="item in dialogDatas.formItems"
            :label="item.label"
          >
            <div v-if="item.isDate">
              <el-date-picker
                v-model="dialogDatas.currentData[item.value]"
                :type="item.dateOption ? item.dateOption.type : 'date'"
                :format="item.dateOption ? item.dateOption.format : 'YYYY/MM/DD'"
                :value-format="item.dateOption ? item.dateOption.valueFormat : 'YYYY/MM/DD'"
                :date-format="item.dateOption ? item.dateOption.dateFormat : ''"
                :time-format="item.dateOption ? item.dateOption.timeFormat : ''"
                :disabled="item.disable"
              />
            </div>

            <div
              v-else-if="item.isSelect"
              style="width: 100%"
            >
              <el-select
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
                filterable
              >
                <el-option
                  v-for="item in item.selectOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </div>

            <div
              v-else-if="item.isImg"
              style="width: 100%"
            >
              <FileUploadVue
                :src="dialogDatas.currentData['FULL_URL'] ? (dialogDatas.currentData['FULL_URL'] + `?t=${Date.now()}`) :''"
                @fileSelected="item.fileSelected"
              >
              </FileUploadVue>
            </div>

            <div v-else-if="item.isSwitch">
              <el-switch
                v-model="dialogDatas.currentData[item.value]"
                inline-prompt
                :active-text="item.trueValue"
                :inactive-text="item.falseValue"
                :active-value="item.trueValue"
                :inactive-value="item.falseValue"
                :disabled="item.disable"
                size="large"
              />
            </div>
            <div
              v-else
              style="width: 100%"
            >
              <el-input
                v-model="dialogDatas.currentData[item.value]"
                :disabled="item.disable"
              />
            </div>
          </el-form-item>
        </el-form>
      </el-scrollbar>

      <template #footer>
        <span>
          <el-button @click="dialogDatas.dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogDatas.confirmBtnClick"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- <el-pagination
      class="marginTop10"
      @size-change="tableDatas.filters.handleSizeChange"
      @current-change="tableDatas.filters.handleCurrentChange"
      :page-sizes="[10, 15, 20, 100]"
      :page-size="tableDatas.filters.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="tableDatas.tableDatasAfterFilter.length"
    >
    </el-pagination> -->

  </div>
</template>
<script>
import { computed, reactive, ref } from 'vue';
import { onMounted, watch } from '@vue/runtime-core';
import { v4 } from 'uuid';
import myAxios from '@/myAxios/myAxios';
import { show, showSuccess, showWarning } from '@/hooks/useMyMessageBox';
import FileUploadVue from '@/components/FileUpload.vue';
import { dayjs } from 'element-plus';
import useMyXlsx from '@/hooks/useMyXlsx';

export default {
  name: '',
  components: {
    FileUploadVue
  },

  setup () {
    let loading = ref(false);
    let addBtnClick = function () {
      const input = document.getElementById('weekInput');
      input.click();
      // showFormDialog();
    };
    let downloadBtnClick = function () {
      // JS下载文件
      let url = 'http://htqdds.haitian.com:9911/qdmes/cher/driver_order_menu/下周菜单.xlsx';
      let a = document.createElement('a');
      a.href = url;
      a.download = '下周菜单.xlsx';
      a.click();
    };

    let fileChanged = async (event) => {
      if (event.target.files.length) {
        // console.log('event.target.files[0] :>> ', event.target.files[0]);
        let xlsx = useMyXlsx();
        let result = await xlsx.getDataFromExcel(event.target.files[0]);
        tableDatas.oritableData = [...result[0]];
        console.log('result :>> ', result);
        const input = document.getElementById('weekInput');
        input.value = '';
      }
      // console.log('1 :>> ', 1);
    };

    let showFormDialog = function (row) {
      if (row) {
        dialogDatas.isNew = false;
        dialogDatas.currentData = { ...row };
      }
      else {
        dialogDatas.isNew = true;
        dialogDatas.currentData = {};
      }
      dialogDatas.dialogFormVisible = true;
    };

    let dialogDatas = reactive({
      dialogFormVisible: false,
      currentData: {},
      isNew: false,
      formItems: [
        // {
        //   "value": "CD_ID",
        //   "label": "菜品ID",
        //   "isDate": false
        // },
        {
          "value": "NAME",
          "label": "菜品名",
          "isDate": false
        },
        {
          "value": "PRICE",
          "label": "价格",
          "isDate": false
        },
        {
          "value": "URL",
          "label": "图片地址",
          "isDate": false,
          "isImg": true,
          "fileSelected": function (event) {
            if (event) {
              dialogDatas.currentData.NEW_URL = event.target.files[0];
            }
            else {
              dialogDatas.currentData.NEW_URL = undefined;
            }
          },
        },
        {
          "value": "DESCRIPTION",
          "label": "描述",
          "isDate": false
        },
        {
          "value": "TYPE",
          "label": "是否为固定每日菜单",
          "isDate": false,
          "isSwitch": true,
          "trueValue": "固定",
          "falseValue": "不固定",
        },
        // {
        //   "value": "EMP_DEPARTMENT",
        //   "label": "部门",
        //   "isDate": false,
        //   "disable": false,
        //   "isSelect": true,
        //   "selectOptions": [
        //     {
        //       "value": "value_1",
        //       "label": "label_1"
        //     },
        //     {
        //       "value": "value_2",
        //       "label": "label_2"
        //     }
        //   ]
        // },
        // {
        //   "value": "DATE_TIME",
        //   "label": "精确到秒的时间(示例,可删除)",
        //   "isDate": true,
        //   "dateOption": {
        //     "type": "datetime",
        //     "format": "YYYY/MM/DD HH:mm:ss",
        //     "dateFormat": "YYYY/MM/DD",
        //     "timeFormat": "HH:mm:ss",
        //     "valueFormat": "YYYY/MM/DD HH:mm:ss"
        //   }
        // },
      ],
      cdList: [],
      confirmBtnClick: async function () {
        loading.value = true;

        if (tableDatas.oritableData.length == 0) {
          loading.value = false;
          console.log(' :>> ',);
          showWarning('请上传下周菜品');
          return;
        }

        //#region 先删除已上传的菜品

        let deleteParamList = [];
        let deleteLength = weekDays.length;
        for (let i = 0; i < deleteLength; i++) {
          let deleteParam = `${weekDays[i].replace(/-/g, '/')}`;
          let result = await myAxios.post('陈帅廷删除食堂每日不固定菜单', deleteParam);
          deleteParamList.push(deleteParam);
        }

        //#endregion

        //#region 上传新菜品

        let insertParamList = [];
        let length = tableDatas.oritableData.length;
        for (let i = 0; i < length; i++) {
          let keys = Object.keys(tableDatas.oritableData[i]);
          let keyLength = keys.length;
          for (let j = 0; j < keyLength; j++) {
            let id = v4();
            let key = keys[j];
            let date = getDateFromKey(key).replace(/-/g, '/');
            let dishName = tableDatas.oritableData[i][key];
            // 获取菜品信息
            let cdItem = dialogDatas.cdList.find(item => item.NAME.trim() == dishName.trim());
            if (cdItem) {
              let dishId = cdItem.CD_ID;
              let formattedString = `${id}\t${date}\t${dishId}`;
              if (insertParamList.some(el => el.endsWith(`${date}\t${dishId}`))) {
                continue;
              }
              else {
                let result = await myAxios.post('陈帅廷添加食堂每日不固定菜单', formattedString);
                insertParamList.push(formattedString);
              }
            }
            else {
              loading.value = false;
              showWarning(`菜品 ${dishName} 不存在,请再次确认!`);
              break;
            }

          }
        }

        //#endregion

        showSuccess('上传成功');
        loading.value = false;

        // let row = dialogDatas.currentData;
        // let CD_ID = row.CD_ID ? row.CD_ID : v4();
        // let NAME = row.NAME;
        // let filename = `${CD_ID}-${NAME}.jpeg`;

        // let uploadResult = ``;
        // if (!row.NEW_URL) {
        //   uploadResult = '未上传图片!';
        // }
        // else if (row.NEW_URL != row.URL) {
        //   uploadResult = await dialogDatas.uploadFile(row.NEW_URL, filename);
        // }
        // else {
        //   uploadResult = '未修改图片,成功!';
        // }
        // if (uploadResult.includes('成功')) {

        //   let params = `${CD_ID}\t${NAME}\t${row.PRICE}`
        //     + `\t${filename}\t${row.DESCRIPTION}\t${row.TYPE}`;
        //   let res = await myAxios.post('陈帅廷添加或修改食堂菜单信息', params);
        //   if (res.includes('成功')) {
        //     loading.value = false;
        //     dialogDatas.dialogFormVisible = false;
        //     showSuccess('提交成功!' + res);
        //     getTableDatas();
        //   }
        //   else {
        //     loading.value = false;
        //     showWarning('更新失败res!' + res);
        //   }
        // }
        // else {
        //   loading.value = false;
        //   showWarning('图片上传失败err!' + uploadResult);
        // }

      },
      uploadFile: function (file, filename) {
        return new Promise((resolve, reject) => {
          var reader = new FileReader();
          reader.onload = async (e) => {
            // let filename = `${`test`}.jpeg`;
            let filePath = `D:\\QDMES\\CHER\\driver_order_menu\\img\\menu\\`;
            let result = await myAxios.uploadFile(e.target.result, filePath, filename);
            if (result.includes('成功')) {
              resolve('上传成功');
            }
            else {
              resolve('上传失败' + result);
            }
          };
          reader.readAsDataURL(file);

        });
      },
      cancelBtnClick: function () {

      }
    });

    let getTableDatas = function () {
      loading.value = true;
      let endDate = dayjs().add(15, 'day').format('YYYY/MM/DD');
      let startDate = dayjs().add(-15, 'day').format('YYYY/MM/DD');
      let params = `${startDate}\t${endDate}`;
      myAxios.get('陈帅廷查询食堂指定时间段菜单', params).then(async res => {
        if (res instanceof Array) {
          loading.value = false;
          tableDatas.oriCalendarList = [...res];
          console.log('res :>> ', res);
          // 获取所有菜品
          dialogDatas.cdList = await myAxios.get('陈帅廷查询食堂可用菜单', '');
          // 获取每日菜品
          for (let i = 0; i < 31; i++) {
            let date = dayjs(startDate).add(i, 'day').format('YYYY-MM-DD');
            tableDatas.oriCalendarCdNameObj[date] = getCdNameFromOriCalendarList(date);
          }
          //   showSuccess('最新数据获取成功!');
        }
        else {
          loading.value = false;
          showWarning('获取数据失败res!' + res);
        }
      }).catch((err) => {
        loading.value = false;
        showWarning('获取数据失败err!' + err);
      });
    };

    onMounted(() => {
      getTableDatas();
    });

    let searchKeys = ['NAME', 'DESCRIPTION'];
    let nextMonday = dayjs().day(1).add(7, 'day');
    let weekDays = [
      nextMonday.add(0, 'day').format('YYYY-MM-DD'),
      nextMonday.add(1, 'day').format('YYYY-MM-DD'),
      nextMonday.add(2, 'day').format('YYYY-MM-DD'),
      nextMonday.add(3, 'day').format('YYYY-MM-DD'),
      nextMonday.add(4, 'day').format('YYYY-MM-DD'),
    ];
    let getKeyFromDate = function (date) {
      let day = dayjs(date).day();
      switch (day) {
        case 1:
          return '周一';
        case 2:
          return '周二';
        case 3:
          return '周三';
        case 4:
          return '周四';
        case 5:
          return '周五';
        case 6:
          return '周六';
        case 0:
          return '周日';
      }
    };
    let getDateFromKey = function (key) {
      switch (key) {
        case '周一':
          return weekDays[0];
        case '周二':
          return weekDays[1];
        case '周三':
          return weekDays[2];
        case '周四':
          return weekDays[3];
        case '周五':
          return weekDays[4];
      }

    };
    let getCdNameFromOriCalendarList = function (date) {
      tableDatas.oriCalendarCdNameObj;
      date = date.replace(/-/g, '/');
      let dateCdList = tableDatas.oriCalendarList.filter(el => el.CD_DATE == date);
      let cdNames = dateCdList.map(el => {
        let cdItem = dialogDatas.cdList.find(el2 => el2.CD_ID == el.CD_NAME);
        if (cdItem) {
          return cdItem.NAME;
        }
        else {
          return el.CD_NAME;
        }
      });
      return cdNames;
    };

    let tableDatas = reactive({
      //表格筛选展示相关代码
      filters: {
        searchText: '',

        //表格翻页相关代码
        currentPage: 1,
        pagesize: 10,
        handleSizeChange (val) {
          tableDatas.filters.pagesize = val;
        },
        handleCurrentChange (val) {
          tableDatas.filters.currentPage = val;
        },
      },
      tableDatasAfterFilter: computed(() => {
        let fData = tableDatas.oritableData;

        if (tableDatas.filters.searchText) {
          let searchText = tableDatas.filters.searchText;
          fData = fData.filter(item => {
            return searchKeys.some(key => {
              return String(item[key]).toLowerCase().includes(searchText.toLowerCase());
            });
          });
        }
        console.log('fData :>> ', fData);

        return fData;
      }),
      tableDatasAfterPage: computed(() => {
        let fData = tableDatas.tableDatasAfterFilter;
        // fData = fData.slice((tableDatas.filters.currentPage - 1) * tableDatas.filters.pagesize, tableDatas.filters.currentPage * tableDatas.filters.pagesize);
        return fData;
      }),

      tableColumns: [
        {
          "type": "index",
          "prop": "",
          "label": "序号",
          "align": "center",
          "width": 60
        },
        // {
        //   "prop": "CD_ID",
        //   "label": "菜品ID",
        //   "align": "center"
        // },
        {
          "prop": "周一",
          "label": `周一(${nextMonday.add(0, 'day').format('YYYY/MM/DD')})`,
          "align": "center"
        },
        {
          "prop": "周二",
          "label": `周二(${nextMonday.add(1, 'day').format('YYYY/MM/DD')})`,
          "align": "center"
        },
        {
          "prop": "周三",
          "label": `周三(${nextMonday.add(2, 'day').format('YYYY/MM/DD')})`,
          "align": "center"
        },
        {
          "prop": "周四",
          "label": `周四(${nextMonday.add(3, 'day').format('YYYY/MM/DD')})`,
          "align": "center"
        },
        {
          "prop": "周五",
          "label": `周五(${nextMonday.add(4, 'day').format('YYYY/MM/DD')})`,
          "align": "center"
        },
        // {
        //   "prop": "operate",
        //   "label": "操作",
        //   "align": "center",
        //   "width": 170,
        // },
      ],
      oritableData: [
      ],
      oriCalendarList: [],
      oriCalendarCdNameObj: {},
      editBtnClick: function (row) {
        showFormDialog(row);
      },
      deleteBtnClick: function (row) {
        loading.value = true;
        let CD_ID = row.CD_ID;

        // let json = `{"CD_ID":"587639ea-d7fd-4b9b-b493-2131db2f3f68","NAME":"手工小馄饨","PRICE":6,"URL":"587639ea-d7fd-4b9b-b493-2131db2f3f68-手工小馄饨.jpeg","DESCRIPTION":"15个/盒，猪肉馅","TYPE":"固定","STATE":"可用"}`
        //   + `{"CD_ID":"587639ea-d7fd-4b9b-b493-2131db2f3f68","NAME":"手工小馄饨","PRICE":6,"URL":"587639ea-d7fd-4b9b-b493-2131db2f3f68-手工小馄饨.jpeg","DESCRIPTION":"15个/盒，猪肉馅","TYPE":"固定","STATE":"可用"}`;
        // let params = `${CD_ID}\t${1}\t${CD_ID}\t${json}`;
        let params = `${CD_ID}\t${'禁用'}`;
        // let name = `陈帅廷添加或修改菜单记录`;
        let name = `陈帅廷修改食堂菜单状态`;
        myAxios.post(name, params).then(res => {
          if (res.includes('成功')) {
            loading.value = false;
            dialogDatas.dialogFormVisible = false;
            showSuccess('删除成功!' + res);
            // ElMessage({
            //   showClose: true,
            //   type: 'success',
            //   message: '删除成功!' + res
            // });
            tableDatas.oritableData.splice(tableDatas.oritableData.indexOf(row), 1);
          }
          else {
            loading.value = false;
            showWarning('删除失败res!' + res);
          }
        }).catch((err) => {
          loading.value = false;
          showWarning('删除失败err!' + err);
        });

      },
    });

    return {
      loading,
      addBtnClick,
      downloadBtnClick,
      fileChanged,
      dialogDatas,
      weekDays,
      getKeyFromDate,
      // getCdNameFromOriCalendarList,
      tableDatas,
    };
  }
}
</script>
<style lang="css" scope>
.el-calendar-table .el-calendar-day {
  height: auto;
}

.marginTop10 {
  margin-top: 10px;
}
.marginTop48 {
  margin-top: 48px;
}
.is-selected {
  color: #1989fa;
  background-color: var(--el-color-success-light-5);
}
</style>

